package com.pospi.xstore.http;

import android.content.Context;
import android.content.SharedPreferences;
import android.util.Log;
import android.widget.Toast;

import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;

import org.apache.http.Header;
import org.apache.http.HeaderElement;
import org.apache.http.ParseException;

/**
 * 访问服务器，接收服务器返回的数据
 */
public class LoadServer {
    public static void getConnect(final Context context, String address, RequestParams params, final AsyncHttpResponseHandler handler) {
        SharedPreferences preferences = context.getSharedPreferences("Token", context.MODE_PRIVATE);
        final String token = preferences.getString("token", "");
        Log.i("token", token);
        AsyncHttpClient client = new AsyncHttpClient();//实例化

        Header[] headerArr = new Header[1];
        headerArr[0] = new Header() {
            @Override
            public String getName() {
                return "token";
            }

            @Override
            public String getValue() {
                return token;
            }

            @Override
            public HeaderElement[] getElements() throws ParseException {
                return new HeaderElement[0];
            }
        };

        client.post(context, address, headerArr, params, null, new AsyncHttpResponseHandler() {
            public void onSuccess(int statusCode, Header[] headers,
                                  byte[] responseBody) {

                handler.onSuccess(statusCode, headers, responseBody);
            }


            @Override
            public void onFailure(int i, Header[] headers, byte[] bytes, Throwable throwable) {
                throwable.printStackTrace();// 把错误信息打印出轨迹来
                try {
                    handler.onFailure(i, headers, bytes, throwable);

                } catch (Exception e){
                    Toast.makeText(context,"网络连接失败，稍后再试",Toast.LENGTH_SHORT).show();
                }

            }
        });
    }
}
